package com.yan.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本工程的一些工具方法
 * 
 * @author luoyong
 * @date 2016-3-26
 */
public final class GzipUtil {

	private static final Logger LOG = LoggerFactory.getLogger(GzipUtil.class.getName());
	private static final String CODE = "UTF-8";
	private static final String DEFAULT_UNIT = "万英镑";

	/**
	 * 压缩GZip
	 * 
	 * @return
	 */
	public static String gZip(String input) {
		byte[] bytes = null;
		GZIPOutputStream gzip = null;
		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream();
			gzip = new GZIPOutputStream(bos);
			gzip.write(input.getBytes(CODE));
			gzip.finish();
			gzip.close();
			bytes = bos.toByteArray();
			bos.close();
		} catch (Exception e) {
			LOG.error("压缩出错：", e);
		} finally {
			IOUtils.closeQuietly(gzip);
			IOUtils.closeQuietly(bos);
		}
		return Base64.encodeBase64String(bytes);
	}

	/**
	 * 解压GZip
	 * 
	 * @return
	 */
	public static String unGZip(String input) {
		byte[] bytes = null;
		String out = input;
		GZIPInputStream gzip = null;
		ByteArrayInputStream bis = null;
		ByteArrayOutputStream bos = null;
		try {
			// bis = new ByteArrayInputStream(Base64.decodeBase64(input));
			bis = new ByteArrayInputStream(input.getBytes());
			gzip = new GZIPInputStream(bis);
			byte[] buf = new byte[1024];
			int num = -1;
			bos = new ByteArrayOutputStream();
			while ((num = gzip.read(buf, 0, buf.length)) != -1) {
				bos.write(buf, 0, num);
			}
			bytes = bos.toByteArray();
			out = new String(bytes, CODE);
			gzip.close();
			bis.close();
			bos.flush();
			bos.close();
		} catch (Exception e) {
			LOG.error("解压出错：", e);
		} finally {
			IOUtils.closeQuietly(gzip);
			IOUtils.closeQuietly(gzip);
			IOUtils.closeQuietly(bos);
		}
		return out;
	}

	/**
	 * int 转成 byte数组
	 * 
	 * @param num
	 * @return
	 */
	public static byte[] intToByteArray(int num) {
		byte[] byteArr = new byte[4];
		// 最低位
		byteArr[0] = (byte) (num & 0xff);
		// 次低位
		byteArr[1] = (byte) ((num >> 8) & 0xff);
		// 次高位
		byteArr[2] = (byte) ((num >> 16) & 0xff);
		// 最高位,无符号右移
		byteArr[3] = (byte) (num >>> 24);
		return byteArr;
	}

	/**
	 * byte数组转成int
	 * 
	 * @param val
	 * @return
	 */
	public static int byteArrayToInt(byte[] arr) {
		return (arr[0] & 0xff) | ((arr[1] << 8) & 0xff00) | ((arr[2] << 24) >>> 8) | (arr[3] << 24);
	}

	public static void main(String args[]) {

		System.out.println(intToByteArray(5));

		System.out.println(byteArrayToInt(intToByteArray(5)));

		System.out.println(gZip("this is a test...") + unGZip("H4sIAAAAAAAAACvJyCxWAKJEhZLU4hI9PT0AKLsGVREAAAA="));

	}
}
